package com.aurora.source.home.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aurora.source.R;
import com.aurora.source.authority.CommodityManagementActivity;
import com.aurora.source.authority.activity.AuthManageActivity;
import com.aurora.source.authority.presenter.ExaminePresenter;
import com.aurora.source.authority.view.IExamineView;
import com.aurora.source.base.BaseActivity;
import com.aurora.source.base.BaseBean;
import com.aurora.source.base.UpdateBean;
import com.aurora.source.center.activity.SourceCenterMainActivity;
import com.aurora.source.constant.AuroraConstants;
import com.aurora.source.entity.SysPermissionEntity;
import com.aurora.source.entity.UserEntity;
import com.aurora.source.event.EventData;
import com.aurora.source.greendao.SysPermissionEntityDao;
import com.aurora.source.source.activity.SettingActivity;
import com.aurora.source.source.bean.UserInfoBean;
import com.aurora.source.util.DpPxUtil;
import com.aurora.source.util.ErrorImgUtil;
import com.aurora.source.util.GreenDaoHelper;
import com.aurora.source.util.StatusBarUtils;
import com.aurora.source.util.UpdaterUtils;
import com.aurora.source.util.netutil.RequestMethod;
import com.aurora.source.util.netutil.SubscriberObserver;
import com.aurora.source.widget.CircleImageView;
import com.aurora.source.widget.GlideImageLoader;
import com.aurora.source.widget.RuntimeRationale;
import com.aurora.source.widget.SimpleToolbar;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity<ExaminePresenter> implements IExamineView {

    @BindView(R.id.tv_left_title)
    TextView tvLeftTitle;
    @BindView(R.id.tv_main_title)
    TextView tvMainTitle;
    @BindView(R.id.tv_right_title)
    TextView tvRightTitle;
    @BindView(R.id.st_toolbar)
    SimpleToolbar stToolbar;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.ll_enterprise_information)
    LinearLayout llEnterpriseInformation;
    @BindView(R.id.ll_resource_center)
    LinearLayout llResourceCenter;
    @BindView(R.id.ll_jurisdiction)
    LinearLayout llJurisdiction;
    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.linearLayout3)
    LinearLayout linearLayout3;
    @BindView(R.id.view3)
    View view3;
    @BindView(R.id.linearLayout2)
    LinearLayout linearLayout2;
    @BindView(R.id.view4)
    View view4;
    @BindView(R.id.cv_image)
    CircleImageView cvImage;
    @BindView(R.id.tv_jurisdiction_name)
    TextView tvJurisdictionName;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.ll_commodity_management)
    LinearLayout llCommodityManagement;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    @BindView(R.id.ll_batch_management)
    LinearLayout llBatchManagement;
    @BindView(R.id.ll_circleIndicator)
    LinearLayout circleIndicator;
    private List<String> bannerList;
    //更新App
    private ProgressDialog mProgressDialog;// 下载进度条
    private AlertDialog mAlertDialog;// 确认弹窗
    private AlertDialog.Builder mBuilder;// 确认弹窗
    private boolean isOnLogin = false;// 是否强制更新
    private boolean isFirst = false;// 非强制更新 只显示一次弹窗
    private int mIndicatorSelectedResId = R.drawable.shape_gray_radius;
    private int mIndicatorUnselectedResId = R.drawable.shape_white_radius;
    private List<ImageView> indicatorImages;

    @Override
    public ExaminePresenter attach() {
        return new ExaminePresenter(this);
    }

    RequestMethod requestMethod;

    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    /**
     * 刷新用户信息
     */
    private void refreshUserInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("userId", userId);
        basePresenter.Examine(activity, params, false);
    }

    /**
     * 刷新UI
     */
    private void refreshUI() {
        UserEntity userEntity = GreenDaoHelper.getDaoSession().getUserEntityDao().loadAll().get(0);
        if (!TextUtils.isEmpty(userEntity.getCompanyName())) {
            tvMainTitle.setText(userEntity.getCompanyName());
        } else {
            tvMainTitle.setText("公司名称");
        }

        //     tvPropertyName.setText(walletDataBean.getName());processTitles bannerPathList
        tvName.setText(userEntity.getUserName());
        tvJurisdictionName.setText(userEntity.getProcessTitles());
        Glide.with(this)
                .load(userEntity.getUserHeadPath())
                .apply(new RequestOptions().placeholder(R.drawable.ico_txiang01))
                .into(cvImage);
        //设置图片集合
        List<String> banners = new ArrayList<>();
        if (bannerList != null && bannerList.size() > 5) { //显示5张吧
            for (int i = 4; i >= 0; i--) {
                banners.add(bannerList.get(i));
            }
        } else if (bannerList != null) {
            banners = bannerList;
        }
        banner.setImages(banners);
        if (banners.size() > 0) {
            banner.start();
        }

        circleIndicator.removeAllViews();
        indicatorImages.clear();
        for (int i = 0; i < banners.size(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DpPxUtil.dp2px(this, 8), DpPxUtil.dp2px(this, 8));
            params.leftMargin = DpPxUtil.dp2px(this, 2);
            params.rightMargin = DpPxUtil.dp2px(this, 2);
            if (i == 0) {
                imageView.setImageResource(mIndicatorSelectedResId);
            } else {
                imageView.setImageResource(mIndicatorUnselectedResId);
            }
            imageView.setLayoutParams(params);
            indicatorImages.add(imageView);
            circleIndicator.addView(imageView);
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        updateApp();
        refreshUserInfo();
    }

    @Override
    public void initData(@Nullable Bundle bundle) {
        requestMethod = new RequestMethod();
        indicatorImages = new ArrayList<>();
        if (bundle != null) {
            bannerList = bundle.getStringArrayList("bannerList");
        }
    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        mProgressDialog = new ProgressDialog(this);
        mBuilder = new AlertDialog.Builder(this);
        mAlertDialog = mBuilder.create();
        EventBus.getDefault().register(this);
        StatusBarUtils.setWindowStatusBarColor(MainActivity.this, R.color.source);
        StatusBarUtils.StatusBarDarkMode(getWindow());
        UserEntity userEntity = GreenDaoHelper.getDaoSession().getUserEntityDao().loadAll().get(0);
        if (!TextUtils.isEmpty(userEntity.getCompanyName())) {
            tvMainTitle.setText(userEntity.getCompanyName());
        } else {
            tvMainTitle.setText("公司名称");
        }
        bannerList = new ArrayList<>();
        //     tvPropertyName.setText(walletDataBean.getName());processTitles bannerPathList
        tvName.setText(userEntity.getUserName());
        tvJurisdictionName.setText(userEntity.getProcessTitles());
        Glide.with(this)
                .load(userEntity.getUserHeadPath())
                .apply(new RequestOptions().placeholder(R.drawable.ico_txiang01))
                .into(cvImage);

        //圆形指示器
        banner.setBannerStyle(0);
        banner.setIndicatorGravity(BannerConfig.CENTER);

        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < indicatorImages.size(); i++) {
                    if (i == position) {
                        indicatorImages.get(i).setImageResource(mIndicatorSelectedResId);
                    } else {
                        indicatorImages.get(i).setImageResource(mIndicatorUnselectedResId);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用

        DisplayMetrics displayMetrics = new DisplayMetrics();
        Display defaultDisplay = this.getWindowManager().getDefaultDisplay();
        defaultDisplay.getMetrics(displayMetrics);
        ViewGroup.LayoutParams layoutParams = banner.getLayoutParams();
        layoutParams.height = displayMetrics.widthPixels / 2;
        layoutParams.width = displayMetrics.widthPixels;
        banner.setLayoutParams(layoutParams);
        /*stToolbar.setRightTitleDrawable(R.drawable.ico_sy_szhi);
        stToolbar.setRightTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(SettingActivity.class, false);
            }
        });*/

    }

    //接收退出登录操作发过来的消息  执行退出应用
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(String message) {
        if (message.equals(EventData.logOut)) {
            hideSoftInput();
            finish();
        }
    }


    @Override
    public void doBusiness() {
        requestPermission(Permission.READ_EXTERNAL_STORAGE, Permission.CAMERA);

    }


    // 申请多个权限
    private void requestPermission(String... permissions) {
        try {
            AndPermission.with(this)
                    .runtime()
                    .permission(permissions)
                    .rationale(new RuntimeRationale())
                    .onGranted(new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> permissions) {
                            // 权限获取成功
                        }
                    })
                    .onDenied(new Action<List<String>>() {
                        @Override
                        public void onAction(@NonNull List<String> permissions) {
                            // 权限获取失败
                            showToast("权限获取失败");

                        }
                    })
                    .start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.ll_commodity_management, R.id.ll_setting, R.id.ll_batch_management, R.id.ll_enterprise_information, R.id.ll_resource_center, R.id.ll_jurisdiction})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_enterprise_information://企业信息
                gotoActivity(EnterpriseInformationActivity.class, false);
                break;
            case R.id.ll_resource_center://溯源中心
                gotoActivity(SourceCenterMainActivity.class, false);
                break;
            case R.id.ll_jurisdiction://授权管理
                SysPermissionEntity sysPermissionEntity = GreenDaoHelper.getDaoSession().getSysPermissionEntityDao().loadAll().get(0);
                if (sysPermissionEntity == null || !sysPermissionEntity.getAddUser()) {
                    showToast("没有权限");
                    return;
                }
                gotoActivity(AuthManageActivity.class, false);
                break;
            case R.id.ll_setting://设置
                gotoActivity(SettingActivity.class, false);
                break;
            case R.id.ll_commodity_management://商品管理
                gotoActivity(CommodityManagementActivity.class, false);
                break;
            case R.id.ll_batch_management://批次管理
                SysPermissionEntity sysPermissionEntity2 = GreenDaoHelper.getDaoSession().getSysPermissionEntityDao().loadAll().get(0);
                /*if(sysPermissionEntity2==null||!sysPermissionEntity2.getAddBatch()){
                    showToast("没有权限");
                    return;
                }*/
                gotoActivity(BatchManagementActivity.class, false);
                break;
        }
    }

    /**
     * 获取用户信息成功
     *
     * @param data
     */
    @Override
    public void onExamineSuccess(UserInfoBean data) {
        //保存用户信息
        UserEntity userEntity = GreenDaoHelper.getDaoSession().getUserEntityDao().loadAll().get(0);
        String pwd = userEntity.getUserPwd();
        Long id = userEntity.getId();
        data.getUserInfoDTO().setUserPwd(pwd);
        data.getUserInfoDTO().setId(id);
        GreenDaoHelper.getDaoSession().getUserEntityDao().insertOrReplace(data.getUserInfoDTO());
        //保存权限信息
        SysPermissionEntity sysPermissionEntity1 = GreenDaoHelper.getDaoSession().getSysPermissionEntityDao().queryBuilder().where(SysPermissionEntityDao.Properties.UserId.eq(userEntity.getUserId())).unique();
        List<String> sysRoleList = data.getUserInfoDTO().getSysRoleList();//权限列表
        if (sysRoleList != null && sysRoleList.size() > 0) {
            //ADD_USER,ADD_BATCH,ADD_LOGISTICS,UPDATE_COMPANY,ADD_PRODUCT
            if (sysRoleList.contains("ADD_USER")) { //添加子账号
                sysPermissionEntity1.setAddUser(true);
            } else {
                sysPermissionEntity1.setAddUser(false);
            }
            if (sysRoleList.contains("ADD_BATCH")) { //添加批次
                sysPermissionEntity1.setAddBatch(true);
            } else {
                sysPermissionEntity1.setAddBatch(false);
            }
            if (sysRoleList.contains("ADD_LOGISTICS")) { //添加物流
                sysPermissionEntity1.setAddLogistics(true);
            } else {
                sysPermissionEntity1.setAddLogistics(false);
            }
            if (sysRoleList.contains("UPDATE_COMPANY")) { //修改公司
                sysPermissionEntity1.setUpdateCompany(true);
            } else {
                sysPermissionEntity1.setUpdateCompany(false);
            }
            if (sysRoleList.contains("ADD_PRODUCT")) { //添加商品
                sysPermissionEntity1.setAddProduct(true);
            } else {
                sysPermissionEntity1.setAddProduct(false);
            }
        } else {
            sysPermissionEntity1.setAddUser(false);
            sysPermissionEntity1.setAddBatch(false);
            sysPermissionEntity1.setAddLogistics(false);
            sysPermissionEntity1.setUpdateCompany(false);
            sysPermissionEntity1.setAddProduct(false);
        }
        //插入权限信息
        GreenDaoHelper.getDaoSession().getSysPermissionEntityDao().insertOrReplace(sysPermissionEntity1);
        bannerList = data.getUserInfoDTO().getBannerPathList();
        refreshUI();//更新UI
    }

    @Override
    public void onExamineFail(String msg) {

    }

    // 判断是否需要更新App
    private void updateApp() {
        if (!mProgressDialog.isShowing() && !mAlertDialog.isShowing()) {
            requestMethod.automaticUpdate(new SubscriberObserver<BaseBean<UpdateBean>>(activity) {
                @Override
                public void onSuccess(BaseBean<UpdateBean> update) {
                    if (update.getCode().equals(AuroraConstants.REQUEST_SUCCESS)) {
                        if (getVersion().compareTo(update.getData().getAppVersion()) < 0 && !isEmpty(update.getData().getAppDownloadUrl())) {
                            String titlle;// 弹窗标题
                            String url = update.getData().getAppDownloadUrl();// 下载地址
                            if (update.getData().getIsForcedUpdate().equals("Y")) {
                                isOnLogin = true;
                                titlle = "本次更新为强制更新";
                            } else {
                                isOnLogin = false;
                                titlle = "本次更新为非强制更新";
                            }
                            if (!isOnLogin && isFirst) {
                                return;
                            }
                            // 下载安装 apk
                            UpdaterUtils.downloadApkFile(activity, url, mProgressDialog, mBuilder, titlle, isOnLogin);
                            isFirst = true;
                        }
                    } else {
                        showToast(update.getMsg());
                    }
                }

                @Override
                public void onError(String msg) {
                    //  showToast(msg);
                }

                @Override
                public void onFinish() {
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
